<template>
  <el-select style="width: 100%" filterable v-model="selectedValue" @change="handleChangeTimezone">
    <template v-for="item in timezoneOptions" :key="item.value">
      <el-option :label="item.label" :value="item.value"></el-option>
    </template>
  </el-select>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useTimezoneSelect } from 'vue-timezone-select';
import type { TimezoneInfo } from 'vue-timezone-select';
import { propTypes } from '@/utils/propTypes';

const props = defineProps({
  /* 编辑器的内容 */
  modelValue: propTypes.string,
  /* 样式 */
  labelStyle: propTypes.string.def('altName')
});

const emit = defineEmits(['update:modelValue', 'change']);
const selectedValue = ref(props.modelValue);
const timezoneInfo = ref<TimezoneInfo | {}>({});
const { timezoneOptions, getSelectedInfo } = useTimezoneSelect({
  labelStyle: props.labelStyle
});

const handleChangeTimezone = (val: string) => {
  timezoneInfo.value = getSelectedInfo(val, timezoneOptions);
  emit('update:modelValue', val);
  emit('change', { value: val, info: timezoneInfo.value });
};
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal !== selectedValue.value) {
      selectedValue.value = newVal;
      if (newVal) {
        timezoneInfo.value = getSelectedInfo(newVal, timezoneOptions);
      }
    }
  }
);
</script>
